"""
提示词管理服务
负责提示词模板的管理
"""

from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
import re

from app.models.prompt_template import PromptTemplate
from app.services.base_service import BaseService
from app.schemas.prompt_template import PromptTemplateCreate, PromptTemplateUpdate


class PromptService(BaseService[PromptTemplate, PromptTemplateCreate, PromptTemplateUpdate]):
    """提示词服务"""
    
    def __init__(self):
        super().__init__(PromptTemplate)
    
    def get_active_templates(self, db: Session) -> List[PromptTemplate]:
        """获取所有激活的提示词模板"""
        return db.query(PromptTemplate).filter(PromptTemplate.is_active == True).all()
    
    def get_public_templates(self, db: Session) -> List[PromptTemplate]:
        """获取公开的提示词模板"""
        return db.query(PromptTemplate).filter(
            and_(
                PromptTemplate.is_active == True,
                PromptTemplate.is_public == True
            )
        ).all()
    
    def get_templates_by_category(self, db: Session, category: str) -> List[PromptTemplate]:
        """根据分类获取提示词模板"""
        return db.query(PromptTemplate).filter(
            and_(
                PromptTemplate.category == category,
                PromptTemplate.is_active == True
            )
        ).all()
    
    def search_templates(
        self, 
        db: Session, 
        query: str,
        category: Optional[str] = None
    ) -> List[PromptTemplate]:
        """搜索提示词模板"""
        search_filter = and_(
            PromptTemplate.is_active == True,
            or_(
                PromptTemplate.name.contains(query),
                PromptTemplate.description.contains(query),
                PromptTemplate.content.contains(query)
            )
        )
        
        if category:
            search_filter = and_(search_filter, PromptTemplate.category == category)
        
        return db.query(PromptTemplate).filter(search_filter).all()
    
    def get_template_variables(self, template_content: str) -> List[str]:
        """提取模板中的变量"""
        # 匹配 {{variable}} 格式的变量
        pattern = r'\{\{([^}]+)\}\}'
        variables = re.findall(pattern, template_content)
        return list(set(variables))  # 去重
    
    def render_template(
        self, 
        template_content: str, 
        variables: Dict[str, str]
    ) -> str:
        """渲染提示词模板"""
        try:
            # 简单的模板渲染，将 {{variable}} 替换为实际值
            rendered = template_content
            for key, value in variables.items():
                placeholder = f"{{{{{key}}}}}"
                rendered = rendered.replace(placeholder, str(value))
            return rendered
        except Exception as e:
            raise ValueError(f"模板渲染失败: {str(e)}")
    
    def increment_usage_count(self, db: Session, template_id: int) -> bool:
        """增加模板使用次数"""
        template = db.query(PromptTemplate).filter(PromptTemplate.id == template_id).first()
        if template:
            template.usage_count += 1
            db.commit()
            return True
        return False
    
    def get_popular_templates(self, db: Session, limit: int = 10) -> List[PromptTemplate]:
        """获取热门提示词模板"""
        return db.query(PromptTemplate).filter(
            PromptTemplate.is_active == True
        ).order_by(PromptTemplate.usage_count.desc()).limit(limit).all()
    
    def create_template(
        self, 
        db: Session, 
        name: str,
        content: str,
        description: Optional[str] = None,
        category: Optional[str] = None,
        tags: Optional[List[str]] = None,
        is_public: bool = False
    ) -> PromptTemplate:
        """创建提示词模板"""
        # 提取模板变量
        variables = self.get_template_variables(content)
        
        template = PromptTemplate(
            name=name,
            description=description,
            content=content,
            variables=variables,
            category=category,
            tags=tags or [],
            is_public=is_public
        )
        
        db.add(template)
        db.commit()
        db.refresh(template)
        return template
    
    def get_template_info(self, template: PromptTemplate) -> Dict[str, Any]:
        """获取模板信息"""
        return {
            "id": template.id,
            "name": template.name,
            "description": template.description,
            "content": template.content,
            "variables": template.variables,
            "category": template.category,
            "tags": template.tags,
            "is_active": template.is_active,
            "is_public": template.is_public,
            "usage_count": template.usage_count,
            "created_at": template.created_at,
            "updated_at": template.updated_at
        }
